package streammuxer

import (
	"fmt"
	"github.com/pion/rtcp"
	"github.com/pion/rtp"
	"net"
	"time"
)

type (
	StreamId          string
	pullId            uint64
	OnPacketFunc      func(info *StreamInfo, data *StreamData)
	OnStreamCloseFunc func(stream *Stream)
)

func NewStreamIdRTP(ssrc uint32, pt uint8) StreamId {
	return StreamId(fmt.Sprintf("rtp_%v_%v", ssrc, pt))
}

// NewStreamIdRTPOrder 排好序的rtp包
func NewStreamIdRTPOrder(ssrc uint32, pt uint8) StreamId {
	return StreamId(fmt.Sprintf("rtp_order_%v_%v", ssrc, pt))
}
func NewStreamIdRTCP(ssrc uint32) StreamId {
	return StreamId(fmt.Sprintf("rtcp_%v", ssrc))
}

type StreamMuxer interface {
	// AddStream 添加推流stream
	AddStream(info StreamInfo) (*Stream, error)
	RemoteStream(*Stream) error
	GetStream(streamId StreamId) (*Stream, bool)
	RangeStream(fnc func(*Stream) bool)

	// AddPull 添加拉流
	AddPull(streamId StreamId, info PullInfo) (*Puller, error)
	RemotePull(puller *Puller) error

	// Write 发送数据
	Write(data *StreamData) error
	Close()
}

type StreamData struct {
	StreamId StreamId
	Data     any
	Addr     net.Addr

	packet *rtp.Packet
	Ntp    time.Time
	sr     *rtcp.SenderReport
}

type StreamInfo struct {
	Id          StreamId // 必选项
	Name        string
	OnNewPuller func(*Puller) // 新拉流者
	OnDelPuller func(*Puller) // 移除拉流者
}

func (p *Puller) GetStreamId() StreamId {
	return p.streamId
}

type PullInfo struct {
	Name          string            // 拉流者的名称
	OnPacket      OnPacketFunc      // 数据包回调
	OnStreamClose OnStreamCloseFunc // 拉取的流不可用了
}

type Puller struct {
	PullInfo
	streamId StreamId // 需要拉流的id
	pullId   pullId
}

func newPuller(pullInfo PullInfo, streamId StreamId, pullId pullId) *Puller {
	return &Puller{
		PullInfo: pullInfo,
		streamId: streamId,
		pullId:   pullId,
	}
}
